<?php

declare(strict_types=1);

namespace App\Controller\Webhook;

use App\Repository\WebhookRepository;
use App\Repository\WebhookRequestRepository;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Yiisoft\Http\Header;
use Yiisoft\Http\Status;
use Yiisoft\Router\CurrentRoute;
use Yiisoft\Router\UrlGeneratorInterface;

final readonly class ClearRequestsAction
{
    public function __construct(
        private WebhookRepository $webhooks,
        private WebhookRequestRepository $requests,
        private ResponseFactoryInterface $responseFactory,
        private UrlGeneratorInterface $urlGenerator,
        private CurrentRoute $currentRoute,
    ) {}

    public function __invoke(ServerRequestInterface $request): ResponseInterface
    {
        $token = $this->currentRoute->getArgument('token');

        if ($token === null) {
            return $this->responseFactory->createResponse(Status::NOT_FOUND);
        }

        $webhook = $this->webhooks->findByToken($token);
        if ($webhook === null) {
            return $this->responseFactory->createResponse(Status::NOT_FOUND);
        }

        $this->requests->deleteForWebhook($webhook['id']);

        $response = $this->responseFactory->createResponse(Status::SEE_OTHER);

        return $response->withHeader(
            Header::LOCATION,
            $this->urlGenerator->generate('webhook.show', ['token' => $token]),
        );
    }
}
